<?php

/*************************************************************************************
 *
 *	FileName: header_php.php
 *	Desc    : add review for product or shop 
 *	Author  : Seal
 *	Date    : 2009-11-8
 *
 *************************************************************************************/

global $sid;
$sid = $sid == "" ? $_REQUEST['sid'] : $sid ;

if( isset($_REQUEST['product_page']) ) 
{
	$pid = $_REQUEST['pid'];
	$product_page = $_REQUEST['product_page'];
}

$shopDAO = GetShopDAO();
$errmsg = GetMessageStack();
$taskMgr = GetTaskManager();
$tags = $shopDAO->GetTags( $sid );
$pageVars = array();

$shopDAO = GetShopDAO();
$shop_paymethod = $shopDAO->GetPayMethod();
$shop_feature = $shopDAO->GetFeature();


if( isset($_POST['action']) && ( $_POST['action'] == 'add_review' || $_POST['action'] == 'modify_review' ) ) 
{
	$score = trim( $_POST['score'] );
	$service = trim( $_POST['service'] );
	$reality = trim( $_POST['reality'] );
	$velocity = trim( $_POST['velocity'] );
	$rate = trim( $_POST['rate'] );
	$content = trim( $_POST['content'] );
	$product_id_lists = SetEmptyIfUndefined( 'product_lists' );
	$paymethod = SetEmptyIfUndefined( 'paymethod' );
	$feature = SetEmptyIfUndefined( 'feature' );
	$tag = SetEmptyIfUndefined( 'tag' );
	$ori_pics = SetEmptyIfUndefined( 'ori_pics' );
	
	//$tags = explode( ' ', $tag );
	$tags = split(" +",$tag);	//modify by bo,多个空格算一个
	$tags = array_unique( $tags );
	foreach( $tags as $key => $value )
		$value = trim($value);
		
	$tag = implode(' ', $tags );
	
	$pic_names = $_POST['picnames'];
	
	//when it is modifying review, the original user's id
	if( isset($_POST['user_id']) )
		$userid = intval($_POST['user_id']);
		
	if( isset($_POST['reviewid']) )
		$reviewid = intval($_POST['reviewid']);

	$coins = 3;
	
	$r = ProcessAction( $_POST['action'] == 'add_review' , $coins);
		
	if( $r === INVALID_PARA && $_POST['action'] == "modify_review" )
	{
		//$_GET['rid'] = $reviewid;
		//DisplayForModify();
		//edp_allow_next_commit();
		
		echo '<script>parent.AfterPublishWithError("' . get_validation_message() . '");</script>';
		edp_exit();
	}
	elseif( $r === true && $_POST['action'] == "modify_review")
	{
		echo '<script>parent.AfterModifyhWithoutError();</script>';
		edp_exit();
	}
	elseif( $r === INVALID_PARA && $_POST['action'] == "add_review")
	{
		$errmsg = GetMessageStack();
	
		// this page is in a iframe, so call the parent function to handle
		echo '<script>parent.AfterPublishWithError("' . get_validation_message('add_review') . '");</script>';
		edp_exit();
	}
	elseif( $r === true && $_POST['action'] == "add_review")
	{ 
		// this page is in a iframe, so call the parent function to handle
		echo '<script>parent.AfterPublishWithoutError();</script>';
		edp_exit();
	}
}
//for review modify in user center my_review module
else if( isset($_GET['rid']) )
{
	DisplayForModify();
}
else
{
	$pageVars['action'] = 'add_review';
	$webUI = GetWebUI();
	$webUI->AssignGlobalVariable( 'add_review', '1');
}


/**********************************************************
 *
 * 	Process Funtions
 *
 **********************************************************/


function DisplayForModify()
{
	global $rid, $pageVars;
	$rid = intval( $_GET['rid'] );
	$pageVars['action'] = 'modify_review';
	ProcessModify();
}


function ProcessAction( $isAddReview, &$coins) 
{
	global $errmsg, $score, $service, $reality, $velocity, $rate,
	$content, $product_id_lists, $paymethod, $feature, $tag,
	$sid, $pic_names, $pid, $product_page, $userid, $reviewid, $ori_pics, $taskMgr;
	
	$reviewDAO = GetReviewDAO();
	$content = edp_db_input( $content );
	$paymethod = edp_db_input( $paymethod );
	$feature = edp_db_input( $feature );
	$tag = edp_db_input( $tag );
	
	//first check whether uesr can edit this review
	if( !$isAddReview ){
		$authorId = GetReviewDAO()->GetReviewAuthorId( $reviewid );
		if( $authorId === false || $authorId != GetLoginUserID() )
			$errmsg->add_session( 'add_review', '没有权限编辑此评论' );
	}
	else
	{
		if($reviewDAO->ReviewNeedWait(GetLoginUserID(), $sid)===true)
			$errmsg->add_session( 'add_review', '一天只能对同一家店铺发表一次评论' );
	}
	
	if( !IsParaOK() )
		return INVALID_PARA;
	
	$paymethod = $paymethod == "" ? "" : implode(',', $paymethod );
	$feature =	$feature == "" ? "" : implode( ',', $feature ) ;

	

	//$review_date = GetCurrentDate();

	// set the $product_id_list to the product_id if this page is
	// for product information, otherwise to the product id list
	global $product_page, $pid;

	if( isset($product_page) && intval($product_page) == 1 ) {
		$product_id_list = "$pid";
		$product_count = 1;
		$product_id = $pid;
		
       		//inset task to Message Queue
       		$taskMgr->AddProductScoreTask( $pid );
	}
	else {
		$temp = split( ",", $product_id_lists );
		$temp = array_unique( $temp );
		$product_id_list = '';

		$product_count = 0;
		foreach( $temp as $key => $value ) {
			if( !edp_is_empty_string($value) ) {
				if( $product_id_list != '' )
					$product_id_list .= ",";

				$product_id_list  = $product_id_list . intval($value);
				$product_count++;
        			//inset task to Message Queue
        			$taskMgr->AddProductScoreTask( $value );
			}
		}
		
		if( $product_count > 0 )
			$coins += 3;
		
		$product_id = 0;
	}


	$product_id_list = edp_db_input( $product_id_list );
	$view_count = 0;
	$flower_count = 0;
	$egg_count = 0;
	$response_count = 0;

	if( $isAddReview ) 
	{
		//echo $product_id;
		//Verify all the product ID list is valid
		if( !edp_is_empty_string($product_id_list) || $product_id > 0 )
		{
			$productDAO = GetProductDAO();
			$result = $productDAO->GetProductForValidation( $product_id_list );
			$product_id_list = '';
			foreach ( $result as $key => $value )
				$product_id_list .= $value['id'] . ',';	
				
			$product_id_list = rtrim( $product_id_list, ',' );
			
			if( $product_id_list == '' && $product_id > 0 )
			{
				echo "illegal access!";
				edp_exit();
			}
		}
		else
			$product_id_list = '';

		/*
		 * 	All check is ok, then upload the pictures
		 */
		$uploaded_files = array();
		$uploader = GetUploder();
		if( $uploader->SaveFiles( $pic_names, $uploaded_files, $errmsg, 'add_review' ) == false )
			return INVALID_PARA;
		
		$pic_count = count( $uploaded_files );
		
		if( $pic_count > 0 )
			$coins += 3;
		
		$reviewDAO->AddReview(GetLoginUserID(), $sid, GetCurrentDate(), $product_id_list,
			$score, $reality, $service, $velocity, $rate, $content, $paymethod,
			$feature, $tag, $view_count, $flower_count, $egg_count, $response_count,
			$pic_count, $product_count, $uploaded_files, $product_id );
		
          //inset task to Message Queue
        $taskMgr->AddShopScoreTask( $sid );
        $data = array( "shop_id"=> $sid, "tag"=>"$tag", "paymethod"=>"$paymethod", "feature"=>"$feature");
        $taskMgr->AddShopInfoTask( $data );
			
		/***************************************
		 * add by bo at 2010-07-26, add notify 
		 * 
		 ***************************************/	
         global $shopDAO;
		 $productDAO = GetProductDAO(); 
		 $eventVar = array();
		 $para =array();
		 $eventVar[] = NORMAL_REVIEW;
		 $first_review = false;	
		 
		 $para['sid']=$sid;
		 
         if($pic_count > 0){
            
            $eventVar[] = REVIEW_INCLUDE_PIC;
         }
	     if($product_count > 0){
            
            $eventVar[] = REVIEW_INCLUDE_PRODUCT;
            $para['pid_list']=$product_id_list;
         }
         if($product_id != 0){//对店铺点评带商品这个为0，单独对商品的点评
         	
            $para['pid']=$product_id;
         }
         
         if($shopDAO->UpdateFirstReviewer($sid, GetLoginUserID(), GetCurrentDate())===true){//update shop first review if have  
           	       
			$first_review = true;
		 }		
		 if($productDAO->UpdateFirstReviewer($product_id_list, GetLoginUserID(), GetCurrentDate())===true){ //upadate products first review if have  
           	       
			$first_review = true;
		 }							
		 if($first_review){
		 	$eventVar[] = FIRST_REVIEW;
		 }
		              
		 $eventDispatcher = GetEventDispatcher();
		 $eventDispatcher->Notify( GetLoginUserID(), $eventVar, $para);
			
		return true;
		
	}
	//comes to modify
	else {
		$params = array();
		$params['id'] = $reviewid;
		$params['user_id'] = GetLoginUserID();
		$params['shop_id'] = $sid;
		$params['review_date'] = GetCurrentDate();
		$params['score'] = $score;
		$params['reality'] = $reality;
		$params['service'] = $service;
		$params['velocity'] = $velocity;
		$params['rate'] = $rate;
		$params['content'] = $content;
		$params['paymethod'] = $paymethod;
		$params['feature'] = $feature;
		$params['tag'] = $tag;
		$params['view_count'] = $view_count;
		$params['flower_count'] = $flower_count;
		$params['egg_count'] = $egg_count;
		$params['response_count'] = $response_count;
		
		
		
		$rid = $reviewid;
		
		$result = $reviewDAO->GetReviewProdPic( $rid );
		if( count($result) == 0 )
		{
			echo "illegal access!";
			edp_exit();
		}
		
		
		// find the pictures that need to be deleted
		$del_pics = array();
		$remain_pics =array();
		
		
		if( $ori_pics != "" )
		{
			foreach( $ori_pics as $key => $value )
			{
				if( intval($value) == 0 )
				{
					echo "illegal access!";
					edp_exit();
				}
			}
		}
		else
			$ori_pics = array();
		
		
		
		$cur_pics = split( ",", $result['pic_id_list'] );
		
		foreach( $cur_pics as $key => $value )
		{
			if( trim($value) == "")
				continue;
				
			if( !in_array( intval($value), $ori_pics) )
				$del_pics[] = $value;
			else
				$remain_pics[] = $value;
		}
		
		
		// find the products that need to be deleted and to be added
		$del_products = array();
		$new_product_id_list = "";
		if( $product_id == 0 )
		{
			$product_id_list = split( ",", rtrim( $product_id_list, ',' ) );
			$cur_products = split( ",", $result['product_id_list'] );
			
			// find ones need to be deleted and also construct the new 
			// product_id_list
			foreach( $cur_products as $key => $value )
			{
				if( !in_array($value, $product_id_list) )
					$del_products[] = $value;
				else
					// keep the original product
					$new_product_id_list .= $value . ',';
			}
			
			
			// find the added product
			foreach( $product_id_list as $key => $value )
			{
				if( !in_array($value, $cur_products) )
					$new_product_id_list .= $value . ',';
			}
		}
		else{
			
			$new_product_id_list = rtrim( $product_id_list, ',' );
			$param['product_review'] = $new_product_id_list;
		}
		
		$uploaded_files = array();
		$uploader = GetUploder();
		if( $uploader->SaveFiles( $pic_names, $uploaded_files, $errmsg, 'add_review' ) == false )
			return INVALID_PARA;
		$pic_count = count( $uploaded_files );
		$params['uploaded_files'] = $uploaded_files;
		
		
		$new_product_id_list = rtrim( $new_product_id_list, ',' );
		$params['pic_count'] = $pic_count - count($del_pics) ;
		
		if( $new_product_id_list == "" )
			$params['product_count'] = 0;
		else
			$params['product_count'] = count( split(",", $new_product_id_list) );
		
		
		$params['product_id_list'] = $new_product_id_list;
		
		
		$del_pics = implode( ",", $del_pics );
		$remain_pics = implode( ",", $remain_pics );
		$del_products = implode( ",", $del_products );
		
		/*
		echo "ori pic ids: " . $result['pic_id_list']. "<br/>";
		echo "del pic ids: " . $del_pics . "<br/>";
		echo "remain pic ids: " . $remain_pics . "<br/>";
		echo "ori pro ids: " .  $result['product_id_list'] . '<br/>';
		echo "cur prod ids: " . $new_product_id_list . '<br/>';
		*/
		/*
		 * 	All check is ok, then upload the pictures
		 */
		//echo "cur prod ids: " . $params['product_count'] . '<br/>';
		//exit();
		
		
		$reviewDAO->UpdateReview( $params, $del_pics, $remain_pics );

        //inset task to Message Queue
        $taskMgr->AddShopScoreTask( $sid );
        $data = array( "shop_id"=> $sid, "tag"=>"$tag", "paymethod"=>"$paymethod", "feature"=>"$feature");
        $taskMgr->AddShopInfoTask( $data );

		return true;

	}
}

function ProcessModify() {
	global $errmsg, $pageVars, $rid, $product_page, $pid;

	$reviewDAO = GetReviewDAO();
	$review = $reviewDAO->GetReviewDetailById($rid);
	if(GetLoginUserID()===false)
	{
		edp_redirect(edp_href_link(PAGENAME_LOGIN));
	}
	else
	{
		if( $review['user_id'] != GetLoginUserID() )
		{
			//$errmsg->add( 'add_review', '没有权限编辑此评论' );
			edp_redirect(edp_href_link(PAGENAME_PAGE_NOT_FOUND));
		}
		else
		{
			$pageVars['review'] = $review;
			$pageVars['pics'] = $reviewDAO->GetReviewPics( $rid );
			
			global $sid;
			$sid = $pageVars['review']['shop_id'];
			
			if( $pageVars['review']['product_id'] >0 )
			{
				$pid = $pageVars['review']['product_id'];
				$product_page = 1;
				return;
			}
			
			$pageVars['products'] = $reviewDAO->GetReviewProducts( $pageVars['review']['product_id_list'] );
		}
	}
	
}

?>
